<template>
  <div class="gov-application-materials">
    <div class="header" v-if="handleType !== 'scan'">
      <!-- <el-button type="success" size="mini" @click="add">新增材料</el-button> -->
      <!-- <el-button type="primary" size="mini" @click="select">选择材料库</el-button> -->
      <el-form ref="form" inline v-model="searchForm" label-width="100px">
        <el-form-item label="材料使用范围">
          <el-select v-model="searchForm.scope" placeholder="材料类型">
            <el-option label="所有材料" value=""></el-option>
            <el-option label="公共材料" value="0"></el-option>
            <el-option label="部门材料" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择材料">
          <!-- <el-select
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="searchMaterial"
            :loading="loading"
          >
            <el-option
              v-for="item in searchMaterialList"
              :key="item.materialId"
              :label="item.materialName"
              :value="item.materialId"
            ></el-option>
          </el-select> -->
          <el-autocomplete
            v-model="searchForm.name"
            :fetch-suggestions="searchMaterial"
            value-key="materialName"
            clearable
            ref="searchFormName"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="materialName" show-overflow-tooltip label="材料名称"></el-table-column>
        <el-table-column prop="materialTypeName" show-overflow-tooltip label="材料类型"></el-table-column>
        <el-table-column prop="channelName" show-overflow-tooltip label="来源渠道"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100" v-if="handleType !== 'scan'">
          <template slot-scope="scope">
            <el-popconfirm @confirm="delHandle(scope.$index)" title="这是一段内容确定删除吗？">
              <el-button type="text" size="small" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- <add
        :materialType="materialType"
        :materialForm="materialForm"
        :materialSourceChannel="materialSourceChannel"
        :materialWhether="materialWhether"
        :visible.sync="visible.add"
        :eventId="eventId"
        @addSuccess="addSuccess"
      /> -->
      <!-- <selectComponent :visible.sync="visible.select" @addSuccess="addSuccess" /> -->
    </div>
  </div>
</template>

<script>
  import axios from 'axios';
  import { queryDict } from '@/api/common';
  export default {
    components: {},
    props: {
      // clone克隆、edit编辑、scan查看
      handleType: {
        type: String
      },
      selected: {
        type: Object,
        default: () => {
          return {};
        }
      },
      catalog: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      return {
        searchForm: {
          name: '',
          oldName: '',
          scope: ''
        },
        materialType: [],
        materialForm: [],
        materialSourceChannel: [],
        materialWhether: [],
        tableData: [],
        loading: false,
        searchMaterialList: []
      };
    },
    watch: {
      selected: {
        handler(val) {
          if (val) {
            this.tableData = JSON.parse(JSON.stringify(val.materials)) || [];
            this.setNames();
          }
        }
      }
    },
    computed: {},
    methods: {
      delHanhdle(index) {
        this.tableData.splice(index, 1);
      },
      // 获取材料类型字典
      getMaterialType() {
        return queryDict({ dict: 'material_type' });
      },
      // 获取材料形式
      getMaterialForm() {
        return queryDict({ dict: 'material_form' });
      },
      // 获取来源渠道
      getMaterialSourceChannel() {
        return queryDict({ dict: 'source_channel' });
      },
      // 获取事项材料是否必须
      getWhether() {
        return queryDict({ dict: 'whether' });
      },
      // 删除材料
      async delHandle(index) {
        this.tableData.splice(index, 1);
      },
      async init() {
        this.loading = true;
        const [res1, res2, res3, res4, res5] = await axios.all([
          this.getMaterialType(),
          this.getMaterialForm(),
          this.getMaterialSourceChannel(),
          this.getWhether()
        ]);
        this.loading = false;
        const { data: data1 } = res1;
        const { data: data2 } = res2;
        const { data: data3 } = res3;
        const { data: data4 } = res4;
        if (data1.success && data2.success && data3.success && data4.success) {
          this.materialType = data1.result || [];
          this.materialForm = data2.result || [];
          this.materialSourceChannel = data3.result || [];
          this.materialWhether = data4.result || [];
          this.setNames();
        }
      },
      setNames() {
        const list = this.tableData;
        list.forEach((i) => {
          let item;
          item = this.materialType.find((j) => {
            return j.item_value == i.materialTypeId;
          });

          i.materialTypeName = item ? item.item_text : '';

          item = this.materialSourceChannel.find((j) => {
            return j.item_value == i.channelId;
          });
          i.channelName = item ? item.item_text : '';
        });
        this.tableData = list;
      },
      // 选择材料
      handleSelect(item) {
        const isEixst = this.tableData.find((e) => {
          return e.materialId === item.materialId;
        });
        if (!isEixst) {
          this.tableData.push(item);
          this.setNames();
        } else {
          this.$message.info('已选择该材料');
        }
        this.searchForm.name = this.searchForm.oldName;
        this.$refs['searchFormName'].focus();
      },
      // 材料搜索
      async searchMaterial(qs, cb) {
        const { scope } = this.searchForm;
        const params = {
          name: qs,
          current: 1,
          size: 50,
          scope
        };
        if (scope == '1') {
          params.departId = this.catalog.deptId;
        } else {
          delete params.deptId;
        }
        const { data } = await axios.request({
          url: `/api/v1/event/material/common/page`,
          method: 'get',
          params
        });
        if (data.success) {
          const { records = [] } = data.result || {};
          this.$nextTick(() => {
            this.searchForm.oldName = qs;
          });
          cb(records);
        }
      },
      // 获取form数据, isValid是否需要验证，暂存不验证，提交验证
      getFormData(isValid) {
        // 验证
        let valid = true;

        if (isValid && this.tableData.length === 0) {
          valid = false;
        }

        return {
          valid,
          data: {
            ids: this.tableData.map((e) => {
              return e.materialId;
            })
          }
        };
      },
      resetField() {
        this.tableData = [];
      }
    },
    created() {},
    mounted() {
      this.init();
    }
  };
</script>
<style lang="scss">
  .gov-application-materials {
    .header {
      margin-bottom: 20px;
    }
    .el-autocomplete {
      width: 340px;
    }
  }
</style>
